import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import goodsApi from '@/api/inwarehouse/goods-api'
import ownerApi from '@/api/inwarehouse/owner-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const isCompleteOptions = [
      { label: '整货', value: true },
      { label: '散货', value: false }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '物料',
      api: goodsApi,
      columns: [
        { prop: 'skuName', label: '物料名称' },
        { prop: 'barCode', label: '物料编码', valueType: 'input', width: 120 },
        // { prop: 'category', label: '分类' },
        { prop: 'specification', label: '规格型号', width: 200 },
        { prop: 'unit', label: '单位', width: 100 },
        { prop: 'price', label: '单价（¥）', width: 100 },
        { prop: 'alertNumber', label: '预警数量', width: 100 },
        { prop: 'operation', label: '操作', slot: true, width: '150', fixed: 'right' }
      ],
      rules: {
        barCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
        skuName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        // ownerId: [{ required: true, message: '请选择货主', trigger: 'blur' }]
      },
      other: {
        getComplete: (val) => {
          if (!val) {
            return '-'
          }
          return data.isCompleteOptions.find(item => {
            return item.value === val
          }).label
        },
        handleOwnerChange: (val) => {
          if (!val) {
            return '-'
          }
          const obj = data.ownerOptions.find(item => {
            return item.id === val
          })
          ctx.editData.ownerName = obj.name
        }
      }
    }))

    const data = reactive({
      ctx,
      isCompleteOptions,
      ownerOptions: []
    })

    const getOwner = async () => {
      const params = { filter: { disabled: false } }
      const res = await ownerApi.list(params)
      data.ownerOptions = res.data.records
    }

    // init
    onMounted(async () => {
      // await getOwner()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
